<?php
namespace yan\sign_google\widgets;

class GoogleLogin extends \yii\base\Widget{
	public $client_id;
	public $redirect_uri;
	public function run(){
		$this->view->registerJsFile('https://accounts.google.com/gsi/client', ['position'=>\yii\web\View::POS_HEAD, 'async'=>true]);
		if(empty($this->redirect_uri)){
			$this->view->registerJs('
			function onGoogleSign(data){
				var post_data = {};
				var c_p = $("[name=\"csrf-param\"]").attr("content");
				var c_v = $("[name=\"csrf-token\"]").attr("content");
				post_data["type"] = "google-login";
				post_data[c_p] = c_v;
				for(var x in data){
					post_data[x] = data[x];
				}
				console.log(post_data);
				$.ajax({
					url:$("#login-form").attr("action"),
					data:post_data,
					type:"post",
					success:function(data){
						console.log(data);
						if(data.url){
							window.location.href=data.url;
						}else if(data.msg){
							POPUP.msg(data.msg);
						}
					},
					error:function(err){
						console.log(err);
					}
				});
			}
			', \yii\web\View::POS_END);
			$setting = 'data-callback="onGoogleSign"';
		}else{
			$setting = 'data-login_uri="'.$this->redirect_uri.'"';
		}
		
		$shtml = '
		<div id="g_id_onload"
		     data-client_id="'.$this->client_id.'"
		     data-context="signin"
		     data-ux_mode="popup"
		     data-accesstype="offline"
		     '.$setting.' 
		     data-auto_prompt="false">
		</div>

		<div class="g_id_signin"
		     data-type="standard"
		     data-shape="rectangular"
		     data-theme="filled_blue"
		     data-text="signin_with"
		     data-size="large"
		     data-logo_alignment="left">
		</div>';
		return $shtml;
	}
}